package com.zzyl.nursing.service.impl;

import java.util.List;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.IdcardUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson2.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.conditions.query.LambdaQueryChainWrapper;
import com.zzyl.common.exception.base.BaseException;
import com.zzyl.common.utils.CodeGenerator;
import com.zzyl.nursing.DTO.*;
import com.zzyl.nursing.domain.*;
import com.zzyl.nursing.mapper.*;
import com.zzyl.nursing.service.IContractService;
import com.zzyl.nursing.service.IElderService;
import com.zzyl.nursing.vo.CheckInConfigVo;
import com.zzyl.nursing.vo.CheckInDetailVo;
import com.zzyl.nursing.vo.CheckInElderVo;
import com.zzyl.nursing.vo.ElderFamilyVo;
import org.jetbrains.annotations.Nullable;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.zzyl.nursing.service.ICheckInService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.transaction.annotation.Transactional;

import java.util.Arrays;

/**
 * 入住信息Service业务层处理
 *
 * @author ruoyi
 * @date 2025-09-09
 */
@Service
public class CheckInServiceImpl extends ServiceImpl<CheckInMapper, CheckIn> implements ICheckInService {
    @Autowired
    private CheckInMapper checkInMapper;
    @Autowired
    private CheckInConfigMapper checkInConfigMapper;
    @Autowired
    private ElderMapper elderMapper;
    @Autowired
    private BedMapper bedMapper;
    @Autowired
    private IContractService iContractService;
    @Autowired
    private ContractMapper contractMapper;



    /**
     * 查询入住信息
     *
     * @param id 入住信息主键
     * @return 入住信息
     */
    @Override
    public CheckIn selectCheckInById(Long id) {
        return getById(id);
    }

    /**
     * 查询入住信息列表
     *
     * @param checkIn 入住信息
     * @return 入住信息
     */
    @Override
    public List<CheckIn> selectCheckInList(CheckIn checkIn) {
        return checkInMapper.selectCheckInList(checkIn);
    }

    /**
     * 新增入住信息
     *
     * @param checkIn 入住信息
     * @return 结果
     */
    @Override
    public int insertCheckIn(CheckIn checkIn) {
        return save(checkIn) ? 1 : 0;
    }

    /**
     * 修改入住信息
     *
     * @param checkIn 入住信息
     * @return 结果
     */
    @Override
    public int updateCheckIn(CheckIn checkIn) {
        return updateById(checkIn) ? 1 : 0;
    }

    /**
     * 批量删除入住信息
     *
     * @param ids 需要删除的入住信息主键
     * @return 结果
     */
    @Override
    public int deleteCheckInByIds(Long[] ids) {
        return removeByIds(Arrays.asList(ids)) ? 1 : 0;
    }

    /**
     * 删除入住信息信息
     *
     * @param id 入住信息主键
     * @return 结果
     */
    @Override
    public int deleteCheckInById(Long id) {
        return removeById(id) ? 1 : 0;
    }

    /**
     * 申请入住
     */
    @Override
    @Transactional
    public void addElder(CheckInApplyDto checkInApplyDto) {
        //入住配置信息
        CheckInConfigDto checkInConfig = checkInApplyDto.getCheckInConfigDto();
        //合同信息
        CheckInContractDto contractInfo = checkInApplyDto.getCheckInContractDto();
        //老人入住请求模型
        CheckInElderDto elderInfo = checkInApplyDto.getCheckInElderDto();
        //家属信息(list)
        List<ElderFamilyDto> checkInInfo = checkInApplyDto.getElderFamilyDtoList();


        //1.检验老人又没有入住
        LambdaQueryWrapper<Elder> wrapper = Wrappers.<Elder>lambdaQuery()
                .eq(Elder::getIdCardNo, elderInfo.getIdCardNo())
                .eq(Elder::getStatus, 1);
        Elder elder = elderMapper.selectOne(wrapper);

        if (ObjectUtil.isNotNull(elder)) {
            throw new BaseException("老人已经入住，请勿重复入住");
        }
        //更新床位
        Bed bed = bedMapper.selectBedById(checkInConfig.getBedId());
        bed.setBedStatus(1);
        int i = bedMapper.updateById(bed);
        if(i==0){
            throw  new BaseException("该床位已有人");
        }
        //--------
        //新增或更新老人

        //拷贝老人信息
        elder = getElder(elderInfo, bed);

        //-------
               //新增的签约

        Contract bean2 = BeanUtil.toBean(contractInfo, Contract.class);
        bean2.setElderName(elder.getName());
        bean2.setElderId(elder.getId());
        bean2.setStartDate(checkInConfig.getStartDate());
        bean2.setEndDate(checkInConfig.getEndDate());
        bean2.setContractNumber(CodeGenerator.generateContractNumber());
        bean2.setStatus(1L);

        iContractService.save(bean2);




        //----
        //新增入住信息
        CheckIn checkIn = new CheckIn();
        checkIn.setElderName(elder.getName());
        checkIn.setElderId(elder.getId());
        checkIn.setIdCardNo(elder.getIdCardNo());
        checkIn.setStartDate(checkInConfig.getStartDate());
        checkIn.setEndDate(checkInConfig.getEndDate());
        checkIn.setNursingLevelName(checkInConfig.getNursingLevelName());
        checkIn.setBedNumber(elder.getBedNumber());
        if (ObjectUtil.isNotNull(checkInInfo)){
            checkIn.setRemark(JSONUtil.toJsonStr(checkInInfo));
        }
        checkInMapper.insert(checkIn);



        //----
        //新增入住配置
        CheckInConfig bean3 = BeanUtil.toBean(checkInConfig, CheckInConfig.class);
        bean3.setCheckInId(checkIn.getId());

        checkInConfigMapper.insert(bean3);

    }

    @Nullable
    private Elder getElder(CheckInElderDto elderInfo, Bed bed) {
        Elder bean = BeanUtil.toBean(elderInfo, Elder.class);
        //填充床位信息
        bean.setBedId(bed.getId());
        bean.setBedNumber(bed.getBedNumber());
        //查询老人是否曾经入住过（有记录且入住条件下状态不等于1
        LambdaQueryWrapper<Elder> eqElder1 = Wrappers.<Elder>lambdaQuery()
                .eq(Elder::getIdCardNo, elderInfo.getIdCardNo())
                .ne(Elder::getStatus, 1);
        Elder elder2 = elderMapper.selectOne(eqElder1);

        if (ObjectUtil.isNotNull(elder2)) {
            //如果是，更新
            bean.setStatus(1);
            this.elderMapper.updateById(bean);

        }else{
            //如果不是，新增

            this.elderMapper.insertElder(bean);
        }
        return bean;
    }

    /**
     * 查询
     * @param id
     * @return
     */
    @Override
    public CheckInDetailVo selectaOne(Long id) {
        //要回的总表
        CheckInDetailVo checkInDetailVo = new CheckInDetailVo();


        //入住配置实体
        CheckInConfigVo checkInConfigVo = new CheckInConfigVo();

        CheckIn checkIn = checkInMapper.selectById(id);
        if(ObjectUtil.isNotNull(checkIn)){
            BeanUtil.copyProperties(checkIn,checkInConfigVo);
        }


       CheckInConfig checkInConfig = checkInConfigMapper.selectOne(new LambdaQueryWrapper<CheckInConfig>().eq(CheckInConfig::getCheckInId,id)  );
        if (ObjectUtil.isNotNull(checkInConfig)){
            BeanUtil.copyProperties(checkInConfig,checkInConfigVo);
        }


        checkInDetailVo.setCheckInConfigVo(checkInConfigVo);
        Long elderId = checkIn.getElderId();
        //老人入住请求模型

        CheckInElderVo checkInElderVo = new CheckInElderVo();

        Elder elder = elderMapper.selectById(elderId);
        if(ObjectUtil.isNotNull(elder)) {
            BeanUtil.copyProperties(elder, checkInElderVo);
        }
        checkInElderVo.setAge(IdcardUtil.getAgeByIdCard(elder.getIdCardNo()));
        checkInDetailVo.setCheckInElderVo(checkInElderVo);

        //老人家属信息

        String remark = checkIn.getRemark();
        if(ObjectUtil.isNotNull(remark)){
            List<ElderFamilyVo> elderFamilyVos = JSON.parseArray(remark, ElderFamilyVo.class);
            checkInDetailVo.setElderFamilyVoList(elderFamilyVos);
        }

        //合同实体
        Contract contract = contractMapper.selectOne(new LambdaQueryWrapper<Contract>()
                .eq(Contract::getElderId, elder.getId()));

        checkInDetailVo.setContract(contract);

        return checkInDetailVo;
    }
}